<template>
  <div>
    <div class="box-border p-12px">
      <el-form ref="formRef" :rules="rules" :model="form" class="mt-12px">
        <div class="mt-16px">
          <SubTitle title="文件导入" />
          <el-form-item label="归属机构" prop="deptId">
            <el-cascader
              v-model="form.deptId"
              clearable
              placeholder="请选择归属机构"
              :options="options"
              :props="cascaderProps"
              :filter-method="sysFilterMethod"
              value-on-clear=""
              filterable
              :disabled="disabledForm"
            />
          </el-form-item>
          <el-form-item label="归属系统" prop="sysId">
            <el-cascader
              v-model="form.sysId"
              placeholder="请选择归属系统"
              value-on-clear=""
              :props="systemCascaderProps"
              :options="systemList"
              :disabled="disabledForm"
              filterable
              :filter-method="sysFilterMethod"
              clearable
          /></el-form-item>
          <el-form-item style="margin-bottom: 10px">
            <Icon icon="svg-icon:tips" />
            <span style="color: #cccccc">归属机构与归属系统至少填写一项</span>
          </el-form-item>
          <el-form-item label="数据保护标准" prop="template">
            <el-select
              v-model="form.template"
              clearable
              placeholder="请选择数据标准"
              :disabled="disabledForm"
              @change="templateChange"
            >
              <el-option
                v-for="(template, templateIndex) in templateList"
                :key="templateIndex"
                :label="template.dataStandardName"
                :value="template.id"
              /> </el-select
          ></el-form-item>
          <el-row>
            <el-form-item
              label="是否进行智能分类分级"
              v-if="props.params.isSmart === '1'"
              style="width: 100%"
              class="pr-5"
            >
              <el-col :span="10">
                <el-radio-group v-model="isSmart" :disabled="disabledForm">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="2">否</el-radio>
                </el-radio-group>
              </el-col>
              <el-col :span="14" class="text-right" v-if="isSmart == 1">
                <el-button class="mr-10px" @click="handleAutoClass" :disabled="disabledForm"
                  >执行自动分类分级</el-button
                >
                <span>
                  <Icon icon="svg-icon:tips" style="vertical-align: middle; margin-bottom: 1px" />
                  <span style="color: #cccccc">执行后将保存当前文件并进行智能分类分级</span>
                </span>
              </el-col>
            </el-form-item>
          </el-row>
          <el-form-item class="col-item" label="选择文件" v-if="!completeClassfication">
            <el-upload
              class="w-90%"
              drag
              :disabled="disabledForm"
              multiple
              v-model:file-list="form.filePath"
              :action="actionUrl"
              :headers="uploadHeaders"
              :before-upload="beforeUpload"
              :on-remove="uploadRemove"
              :on-success="uploadSuccess"
              :on-error="uploadError"
            >
              <!-- v-model:file-list="fileList" -->
              <el-icon class="el-icon--upload">
                <UploadFilled />
              </el-icon>
              <div class="el-upload__text"> 将文件拖至此处，或<em>点击选择</em> </div>
              <p>支持文件类型： {{ fileSuffix.join('、') }}</p>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
      <el-button
        @click="addRow(formData.list.length - 1)"
        v-if="isSmart === 2 || props.params.isSmart === '2'"
        >新增数据</el-button
      >
      <el-button
        @click="syncData()"
        v-if="isSmart === 2 || props.params.isSmart === '2'"
        >同步</el-button
      >
      <!-- <el-button @click="openTool" v-if="isSmart === 2 || props.params.isSmart === '2'"
        >从工具结果导入</el-button
      > -->
      <el-form ref="formTableRef" :model="formData" class="mt-12px">
        <el-table :data="formData.list">
          <el-table-column width="100px" label="" show-overflow-tooltip fixed="left">
            <template #default="{ row }">
              <div style="color: rgb(245, 108, 108)">
                {{ row.exists ? '已存在' : '' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="150px" label="名称" show-overflow-tooltip fixed="left">
            <template #default="scope">
              <el-form-item
                :prop="`list[${scope.$index}]fileName`"
                :rules="[{ required: true, message: `名称不能为空` }]"
              >
                <ns-input v-model="formData.list[scope.$index].fileName" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="文件类型" min-width="100px">
            <template #default="scope">
              <el-form-item
                :prop="`list[${scope.$index}]fileType`"
                :rules="[{ required: true, message: `文件类型不能为空` }]"
              >
                <ns-input v-model="formData.list[scope.$index].fileType" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="文件大小" min-width="100px">
            <template #default="scope">
              <el-form-item
                :prop="`list[${scope.$index}]fileSize`"
                :rules="[{ required: true, message: `文件大小不能为空` }]"
              >
                <ns-input v-model="formData.list[scope.$index].fileSize" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            width="150px"
            v-for="(column, columnIndex) in columnList"
            :key="columnIndex"
            :label="column.name ? column.name : `字段${columnIndex + 1}`"
          >
            <template #default="scope">
              <!-- <el-form-item
              :prop="`institutionFiled${column.index}`"
              :rules="[{ required: column.required == '1', message: `${column.name}不能为空` }]"
            > -->
              <div>
                <el-form-item
                  v-if="column.index == '1'"
                  :prop="`list[${scope.$index}][institutionFiled${column.index}]`"
                  :rules="[
                    {
                      required: column.required == '1' && itemRequired,
                      message: `${column.name}不能为空`
                    }
                  ]"
                >
                  <el-cascader
                    :filter-method="sysFilterMethod"
                    @change="(e) => classChange(e, column.index, scope.$index)"
                    placeholder="请选择分类"
                    v-model="formData.list[scope.$index][`institutionFiled${column.index}`]"
                    :options="classOptions"
                    :props="{
                      value: 'field1',
                      label: 'field1_name',
                      checkStrictly: true,
                      expandTrigger: 'hover',
                      emitPath: false
                    }"
                    filterable
                  />
                </el-form-item>
                <el-form-item
                  v-else-if="column.index == '2'"
                  :prop="`list[${scope.$index}][institutionFiled${column.index}]`"
                  :rules="[
                    {
                      required: column.required == '1' && itemRequired,
                      message: `${column.name}不能为空`
                    }
                  ]"
                >
                  <el-select
                    v-model="formData.list[scope.$index][`institutionFiled${column.index}`]"
                    placeholder="请选择"
                    @change="institutionFiledChange(column.index, scope.$index)"
                  >
                    <el-option
                      v-for="item in cascaderAllOptions?.[scope.$index]?.[
                        `field${column.index - 1}`
                      ]"
                      :key="item[`field${column.index}`]"
                      :value="item[`field${column.index}`]"
                      :label="item[`field${column.index}_name`]"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="`list[${scope.$index}][institutionFiled${column.index}]`"
                  :rules="[
                    {
                      required: column.required == '1' && itemRequired,
                      message: `${column.name}不能为空`
                    }
                  ]"
                  v-else-if="column.index == '3' && dropdownData"
                >
                  <el-select
                    v-model="formData.list[scope.$index][`institutionFiled${column.index}`]"
                    placeholder="请选择"
                    clearable
                    allow-create
                    filterable
                    @change="
                      () => {
                        institutionFiledChange(column.index, scope.$index)
                        timeFiledChange(scope.$index)
                      }
                    "
                  >
                    <el-option
                      v-for="item in cascaderAllOptions?.[scope.$index]?.[
                        `field${column.index - 1}`
                      ]"
                      :key="item[`field${column.index}`]"
                      :value="item[`field${column.index}`]"
                      :label="item[`field${column.index}`]"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="`list[${scope.$index}][institutionFiled${column.index}]`"
                  :rules="[
                    {
                      required: column.required == '1' && itemRequired,
                      message: `${column.name}不能为空`
                    }
                  ]"
                  v-else-if="column.fillingMethod == '输入框'"
                >
                  <ns-input
                    v-model="formData.list[scope.$index][`institutionFiled${column.index}`]"
                    clearable
                    placeholder="请输入"
                  />
                </el-form-item>
                <el-form-item
                  :prop="`list[${scope.$index}][institutionFiled${column.index}]`"
                  :rules="[
                    {
                      required: column.required == '1' && itemRequired,
                      message: `${column.name}不能为空`
                    }
                  ]"
                  v-else-if="column.fillingMethod == '选择器' && dropdownData"
                >
                  <el-select
                    clearable
                    v-model="formData.list[scope.$index][`institutionFiled${column.index}`]"
                    placeholder="请选择"
                    @change="institutionFiledChange(column.index, scope.$index)"
                  >
                    <el-option
                      v-for="item in cascaderAllOptions?.[scope.$index]?.[
                        `field${column.index - 1}`
                      ]"
                      :key="item[`field${column.index}`]"
                      :value="item[`field${column.index}`]"
                      :label="item[`field${column.index}`]"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="`list[${scope.$index}][institutionFiled${column.index}]`"
                  :rules="[
                    {
                      required: column.required == '1' && itemRequired,
                      message: `${column.name}不能为空`
                    }
                  ]"
                  v-else-if="column.fillingMethod == '日期'"
                >
                  <el-date-picker
                    style="width: 100%"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    v-model="formData.list[scope.$index][`institutionFiled${column.index}`]"
                    type="date"
                    placeholder="选择日期"
                  />
                </el-form-item>
              </div>
              <!-- </el-form-item> -->
            </template>
          </el-table-column>
          <el-table-column
            width="150px"
            v-for="(extend, extendIndex) in extendList"
            :key="extendIndex"
            :label="extend.name ? extend.name : `字段${extendIndex + 1}`"
          >
            <template #default="scope">
              <div>
                <el-form-item
                  :prop="`list[${scope.$index}][field${extend.index}]`"
                  :rules="[
                    {
                      required: extend.required == '1' && itemRequired,
                      message: `${extend.name}不能为空`
                    }
                  ]"
                  v-if="extend.index == '3'"
                >
                  <el-select
                    v-model="formData.list[scope.$index][`field${extend.index}`]"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in levelList"
                      :key="item.levelCode"
                      :label="item.levelName"
                      :value="item.levelCode"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="`list[${scope.$index}][field${extend.index}]`"
                  :rules="[
                    {
                      required: extend.required == '1' && itemRequired,
                      message: `${extend.name}不能为空`
                    }
                  ]"
                  v-else-if="extend.fillingMethod == '输入框'"
                >
                  <ns-input
                    v-model="formData.list[scope.$index][`field${extend.index}`]"
                    clearable
                    placeholder="请输入"
                  />
                </el-form-item>
                <el-form-item
                  :prop="`list[${scope.$index}][field${extend.index}]`"
                  :rules="[
                    {
                      required: extend.required == '1' && itemRequired,
                      message: `${extend.name}不能为空`
                    }
                  ]"
                  v-else-if="extend.fillingMethod == '选择器'"
                >
                  <el-select
                    clearable
                    v-model="formData.list[scope.$index][`field${extend.index}`]"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(option, optionIndex) in extend.presetContentMap"
                      :key="optionIndex"
                      :label="option"
                      :value="option"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="`list[${scope.$index}][field${extend.index}]`"
                  :rules="[
                    {
                      required: extend.required == '1' && itemRequired,
                      message: `${extend.name}不能为空`
                    }
                  ]"
                  v-else-if="extend.fillingMethod == '日期'"
                >
                  <el-date-picker
                    style="width: 100%"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    v-model="formData.list[scope.$index][`field${extend.index}`]"
                    type="date"
                    placeholder="选择日期"
                    @change="dateChange(scope.$index, extend.index)"
                  />
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            width="150px"
            label="操作"
            show-overflow-tooltip
            fixed="right"
            v-if="!completeClassfication"
          >
            <template #default="scope">
              <el-button
                :icon="Minus"
                size="small"
                circle
                class="ml-12px"
                @click="delRow(scope.$index)"
              />
              <el-button
                :icon="Plus"
                size="small"
                circle
                class="ml-12px"
                @click="addRow(scope.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <ImportForm ref="importFormRef" @success="fingerSuccess" />
    </div>
    <div>
      <el-button
        type="primary"
        @click="saveAndAudit"
        v-if="isSmart === 2 || props.params.isSmart === '2'"
        :loading="confirmLoading"
        :disabled="isSave"
        >保存并提交审核</el-button
      >
      <el-button type="primary" @click="nextStep" :loading="confirmLoading" :disabled="isSave"
        >保存</el-button
      >
      <el-button @click="closeOutDrawer">取消</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import ImportForm from './ImportForm.vue'
import { Plus, Minus } from '@element-plus/icons-vue'
import { infoPage } from '@/api/dataStandards/info/index'
import * as assuranceApi from '@/api/dataStandards/assurance/index'
import { getAssetByLevel, assetUpdateLevelList } from '@/api/assetDetail'
import {
  valueConfGetByValue,
  valueConfGetByValueTree,
  valueConfFieldValue
} from '@/api/dataStandards/assuranceValue/index'
import SubTitle from '@/components/SubTitle/index.vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { sysFilterMethod } from '@/utils/selectFilter'
import { handleTree } from '@/utils/tree'
import useCascader from '@/hooks/event/useCascader'
import { fileSuffix } from '@/utils/uploadTypes'
import {
  assetUploadFile2,
  assetMessageCreate2,
  assetMessageCreate2AutoAudit,
  assetUploadFile,
  assetExecClassification,
  assetExecClassificationAsync,
  getBatchAssetInfo
} from '@/api/assetList'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { levelPage } from '@/api/strategyManage/level/index'
import dayjs from 'dayjs'
import { ElLoading } from 'element-plus'
const isSave = ref(false)
const message = useMessage() // 消息弹窗
const { proxy } = getCurrentInstance() as any
const formRef = ref()
const formData = reactive({ list: [] })
const formTableRef = ref()
const flattenDownList = ref([])
const confirmLoading = ref(false)
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  closeOutDrawer: Function
})
const loadingMark = ref(null)
const completeClassfication = ref(false)
const disabledForm = ref(false)
const isSmart = ref(1)
const classOptions = ref([])
const cascaderAllOptions = ref([])
const cascaderData = ref([])
const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}

const fileList = ref<any[]>([])
const fileListCopy = ref<any[]>([])

const actionUrl: string = import.meta.env.VITE_UPLOAD_URL
const uploadHeaders = ref({
  Authorization: 'Bearer ' + getAccessToken(),
  'tenant-id': getTenantId()
})

const handleAutoClass = async () => {
  disabledForm.value = true
  if (formData.list.length == 0) {
    ElMessage.error('文件列表不能为空')
    disabledForm.value = false
    return
  }
  const loading = ElLoading.service({
    lock: true,
    text: '执行自动分类分级中',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  itemRequired.value = false
  formRef.value.validate(async (valid) => {
    if (valid) {
      formTableRef.value.validate(async (valid2) => {
        if (valid2) {
          try {
            isSave.value = true
            confirmLoading.value = true
            smartUpload(true, loading.close)
          } catch {
            loading.close()
          } finally {
            confirmLoading.value = false
            isSave.value = false
          }
        }
        confirmLoading.value = false
      })
    }
    confirmLoading.value = false
  })
}

function filterFileFields(fileData) {
  // 获取需要保留的 index 列表
  const institutionIndexes = columnList.value.map((item) => item.index)
  const fieldIndexes = extendList.value.map((item) => item.index)

  // 创建新对象（不修改原对象）
  const result = { ...fileData }

  // 处理 institutionFiledX 字段
  for (let i = 1; i <= 20; i++) {
    const key = `institutionFiled${i}`
    if (!institutionIndexes.includes(i)) {
      result[key] = ''
    }
  }

  // 处理 fieldX 字段
  for (let i = 1; i <= 20; i++) {
    const key = `field${i}`
    if (!fieldIndexes.includes(i)) {
      result[key] = ''
    }
  }
  result.handClassification = result.institutionFiled1 || ''
  result.handLevel = result.institutionFiled2 || ''
  result.secretDeadline = result.institutionFiled3 || ''
  result.secretStartTime = result.field1 || ''
  result.deadlineTime = result.field2 || ''
  result.deadlineLevel = result.field3 || ''
  return result
}

const importFormRef = ref()
const fingerSuccess = (e) => {
  const data = e.map((item) => {
    return {
      ...item,
      deptId: form.value.deptId == '' ? '0' : form.value.deptId,
      sysId: form.value.sysId,
      template: form.value.template
    }
  })
  formData.list = formData.list.concat(data)
}

const beforeUpload = (file: any) => {
  if (!fileSuffix.includes(file.name.split('.')[file.name.split('.').length - 1])) {
    ElMessage.error('请上传正确格式的文件')
    return false
  }
  if ((form.value.deptId || form.value.sysId) && form.value.template) {
    return true
  } else {
    ElMessage.warning('请选择必填内容！')
    return false
  }
}

const timer = ref<any>(null)
// 上传成功提示
const uploadSuccess = (res: any, file, files): void => {
  console.log(`files -->`, files)
  if (res.code === 1001003003) {
    uploadError(res)
    form.value.filePath.pop()
    return
  } else {
    let { data } = res
    fileList.value.push(data)
    fileListCopy.value.push(data)
    if (fileListCopy.value.length == files.length) {
      getAfterFile()
    }
  }
}
//上传失败提示
const uploadError = (res: any): void => {
  proxy.$message.error(res.message)
}
const uploadRemove = (res: any): void => {
  let { response } = res
  let index = fileListCopy.value.findIndex((item) => item.id == response?.data?.id)
  if (index >= 0) {
    fileList.value.splice(index, 1)
    fileListCopy.value.splice(index, 1)
  }
}

let fileInfo2: any[] = []
const getAfterFile = async () => {
  if (!loadingMark.value) {
    loadingMark.value = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }
  const fileListChunks = []

  for (let i = 0; i < fileList.value.length; i += 6) {
    fileListChunks.push(fileList.value.slice(i, i + 6))
  }
  const allRequests = fileListChunks.map((chunk) =>
    assetUploadFile2({
      deptId: form.value.deptId == '' ? '0' : form.value.deptId,
      sysId: form.value.sysId,
      template: form.value.template,
      fileList: chunk,
      submitStatus: props.params.submitStatus || ''
    })
  )
  try {
    const results = await Promise.all(allRequests)
    results.forEach((result, index) => {
      // 成功的请求
      formData.list = formData.list.concat(...result)
      fileInfo2.push(...result)
    })
    formData.list.map((item, idx) => {
      item.institutionFiled1 && classChange(item.institutionFiled1, 1, idx)
    })
    fileList.value = []
    loadingMark.value.close()
    loadingMark.value = null
  } catch {
    loadingMark.value.close()
    loadingMark.value = null
  }
}

const form = ref({
  deptId: '',
  sysId: '',
  template: null,
  filePath: []
})

const itemRequired = ref(true)

const isRequired = computed(() => {
  return !form.value.deptId && !form.value.sysId
})
const rules = computed(() => ({
  deptId: [{ required: isRequired.value, message: '归属机构不能为空', trigger: 'change' }],
  sysId: [{ required: isRequired.value, message: '归属系统不能为空', trigger: 'change' }],
  template: [{ required: true, message: '数据保护标准不能为空', trigger: 'change' }]
}))

const delRow = (index) => {
  formData.list.splice(index, 1)
  cascaderAllOptions.value.splice(index, 1)
}
const syncData = () => {
  const list = formData.list;

  if (!list || list.length === 0) return;

  const firstItem = list[0];

  // 遍历后续的每一个元素
  for (let i = 1; i < list.length; i++) {
    const currentItem = list[i];

    // 遍历第一个元素的所有属性
    for (const key in firstItem) {
      if (firstItem.hasOwnProperty(key)) {
        // 判断第一个元素该属性非空，且当前项对应属性为空时才复制
        if (
          firstItem[key] !== null &&
          firstItem[key] !== undefined &&
          firstItem[key] !== '' &&
          (currentItem[key] === null ||
           currentItem[key] === undefined ||
           currentItem[key] === '')
        ) {
          currentItem[key] = firstItem[key];
        }
      }
    }
  }
}
const addRow = (index) => {
  const fileRow = {
    dataSourceName: '离线上传',
    source: 3,
    fileName: '',
    fileType: '',
    fileSize: '',
    deptId: form.value.deptId == '' ? '0' : form.value.deptId,
    // deptName: formData.list[0].deptName,
    sysId: form.value.sysId,
    // sysName: formData.list[0].sysName,
    submitStatus: '1',
    auditStatus: '',
    dataType: 'file',
    field1: null,
    field2: null,
    field3: null,
    field4: null,
    field5: null,
    field6: null,
    field7: null,
    field8: null,
    field9: null,
    field10: null,
    field11: null,
    field12: null,
    field13: null,
    field14: null,
    field15: null,
    field16: null,
    field17: null,
    field18: null,
    field19: null,
    field20: null,
    institutionFiled1: null,
    institutionFiled2: null,
    institutionFiled3: null,
    institutionFiled4: null,
    institutionFiled5: null,
    institutionFiled6: null,
    institutionFiled7: null,
    institutionFiled8: null,
    institutionFiled9: null,
    institutionFiled10: null,
    institutionFiled11: null,
    institutionFiled12: null,
    institutionFiled13: null,
    institutionFiled14: null,
    institutionFiled15: null,
    institutionFiled16: null,
    institutionFiled17: null,
    institutionFiled18: null,
    institutionFiled19: null,
    institutionFiled20: null
  }
  formData.list.splice(index + 1, 0, fileRow)
  const levelData = levelOptions.value?.map((ite) => {
    return {
      ...ite,
      disabled: false
    }
  })
  tempLevelList.value.splice(index + 1, 0, { data: levelData })
}

async function processArrayInBatches(array, processBatch) {
  const batchPromises = []

  for (let i = 0; i < array.length; i += 4) {
    const batch = array.slice(i, i + 4) // 每次取最多4个元素作为一批
    batchPromises.push(processBatch(batch)) // 立即发起请求
  }

  // 等待所有批次处理完成
  return await Promise.all(batchPromises)
}

const saveAndAudit = () => {
  if (formData.list.length == 0) {
    ElMessage.error('文件列表不能为空')
    return
  }
  itemRequired.value = true
  formRef.value.validate(async (valid) => {
    if (valid) {
      formTableRef.value.validate(async (valid2) => {
        if (valid2) {
          try {
            isSave.value = true
            confirmLoading.value = true
            if (isSmart.value === 2 || props.params.isSmart === '2') {
              const list = formData.list.map((item) => {
                const newItem = filterFileFields(item)
                return {
                  ...newItem,
                  template: form.value.template,
                  submitStatus: '1'
                }
              })

              const data = await processArrayInBatches(list, assetMessageCreate2AutoAudit)
              if (data) {
                props.params.callBack()
                props.closeOutDrawer()
              }
            }
          } catch {
          } finally {
            confirmLoading.value = false
            isSave.value = false
          }
        }
        confirmLoading.value = false
      })
    }
    confirmLoading.value = false
  })
}

const nextStep = async () => {
  if (formData.list.length == 0) {
    ElMessage.error('文件列表不能为空')
    return
  }
  confirmLoading.value = true
  if (!completeClassfication.value) {
    itemRequired.value = false
    formRef.value.validate(async (valid) => {
      if (valid) {
        formTableRef.value.validate(async (valid2) => {
          if (valid2) {
            try {
              isSave.value = true
              if (isSmart.value === 2 || props.params.isSmart === '2') {
                let levelEqual = false
                const list = formData.list.map((item) => {
                  if (item.institutionFiled2) {
                    if (item.field3 == item.institutionFiled2) {
                      message.warning('到期后等级不能为当前等级')
                      levelEqual = true
                      confirmLoading.value = false
                    }
                  }
                  const newItem = filterFileFields(item)
                  return {
                    ...newItem,
                    template: form.value.template,
                    submitStatus: '1'
                  }
                })
                if (!levelEqual) {
                  list.map((item) => {
                    return {
                      ...filterFileFields(item),
                      deptId: (item.deptId = form.value.deptId == '' ? '0' : form.value.deptId),
                      sysId: (item.sysId = form.value.sysId)
                    }
                  })
                  const data = await processArrayInBatches(list, assetMessageCreate2)
                  if (data) {
                    props.params.callBack()
                    props.closeOutDrawer()
                    confirmLoading.value = false
                  }
                }
              } else if (isSmart.value === 1) {
                smartUpload(false)
              }
            } catch {
              confirmLoading.value = false
            } finally {
              isSave.value = false
              confirmLoading.value = false
            }
          }
          confirmLoading.value = false
        })
      }
      confirmLoading.value = false
    })
    confirmLoading.value = false
  } else {
    try {
      const submitData = formData.list.map((item) => {
        return {
          ...item,
          handClassification: item.institutionFiled1 || item.classification,
          handLevel: item.institutionFiled2 || item.level,
          secretDeadline: item.institutionFiled3,
          secretStartTime: item.field1,
          deadlineTime: item.field2,
          deadlineLevel: item.field3,
          submitStatus: '1'
        }
      })
      const data = await assetUpdateLevelList(submitData)
      if (data) {
        message.success('操作成功')
        props.params.callBack()
        props.closeOutDrawer()
      }
    } finally {
      confirmLoading.value = false
    }
  }
}

const smartUpload = async (isAuto, close) => {
  let levelEqual = false
  const list = formData.list.map((item) => {
    if (item.institutionFiled2) {
      if (item.field3 == item.institutionFiled2) {
        message.warning('到期后等级不能为当前等级')
        disabledForm.value = false
        levelEqual = true
        confirmLoading.value = false
        close && close()
      }
    }
    const newItem = filterFileFields(item)
    return {
      ...newItem,
      template: form.value.template,
      submitStatus: '1'
    }
  })
  if (levelEqual) {
    return
  }
  await processArrayInBatches(list, assetMessageCreate2)
  const formData2 = {
    ids: fileInfo2.map((item) => item.id),
    template: form.value.template,
    objectType: 3
  }
  let res = ''
  if (!isAuto) {
    res = await assetExecClassification(formData2)
  } else {
    res = await assetExecClassificationAsync(formData2)
  }

  if (res) {
    if (!isAuto) {
      message.success('操作成功')
      props.params.callBack()
      props.closeOutDrawer()
    } else {
      const ids = formData.list.map((item) => {
        return item.id
      })
      const res = await getBatchAssetInfo({ ids })
      formData.list = res
      formData.list.map((item, idx) => {
        item.institutionFiled1 = item.handClassification || item.classification
        item.institutionFiled1 && classChange(item.institutionFiled1, 1, idx)
      })
      close && close()
      completeClassfication.value = true
      confirmLoading.value = false
      message.success('自动分类分级成功')
    }
  } else {
    disabledForm.value = false
    confirmLoading.value = false
    close && close()
  }
}

// 分类修改
let classChange = function () {}
let institutionFiledChange = function () {}

// 数据选择修改后，控制后面字段的修改

const dateChange = (scopeIndex, index) => {
  if (index == '1') {
    timeFiledChange(scopeIndex)
  }
}

const timeFiledChange = (scopeIndex) => {
  let convertedTime = convertTimeFormat(formData.list[scopeIndex].institutionFiled3)
  if (!convertedTime) {
    let currentClass = allLevelList.value.find(
      (item) => item.levelCode == formData.list[scopeIndex].institutionFiled2
    )

    convertedTime =
      convertTimeFormat(currentClass?.deadlineTimeNum + currentClass?.deadlineTimeUnit) || {}
  }
  // field1数据为空时
  if (formData.list[scopeIndex].field1) {
    formData.list[scopeIndex].field2 = dayjs(formData.list[scopeIndex].field1)
      .add(Number(convertedTime.num), convertedTime.unit)
      .format('YYYY-MM-DD HH:mm:ss')
  } else {
    formData.list[scopeIndex].field2 = null
  }
}
// 时间格式转换
function convertTimeFormat(timeString) {
  if (!timeString) {
    return
  }
  // 匹配数字和单位部分的正则表达式
  const regex = /(\d+)\s*([^0-9\s]+)/
  // 匹配结果

  const match = timeString.match(regex)

  const unitMap = new Map([
    ['年', 'year'],
    ['月', 'month'],
    ['天', 'day'],
    ['日', 'day']
  ])

  // 如果匹配成功，则返回 num 和 unit 对象
  if (match) {
    //单位不对则退出
    if (!unitMap.get(match[2])) {
      return false
    }
    return {
      num: parseInt(match[1]),
      unit: unitMap.get(match[2])
    }
  } else {
    // 如果匹配失败，返回空对象
    return false
  }
}

const templateChange = async () => {
  await getClassLevelList(form.value.template)
  getInfoList(form.value.template)
  getAssuranceList(form.value.template)
  // getClassificationTree(form.value.template)
  await getDownList(form.value.template)
  formData.list.map((item) => {
    Object.keys(item).forEach((key) => {
      if (key.startsWith('institutionFiled') || key.startsWith('field')) {
        item[key] = ''
      }
    })
    return {
      ...item,
      template: form.value.template || props.params.template,
      // 等级下拉回显
      field3: item.field3 && Number(item.field3)
    }
  })
}

const extendList = ref([
  {
    index: '1',
    name: '',
    required: '',
    fillingMethod: '输入框',
    presetContentMap: []
  }
])
// 获取模板扩展字段列表
const getInfoList = async (template) => {
  const data = await infoPage({
    page: 1,
    pageSize: 20,
    dataStandardId: template || props.params.template,
    display: '1'
  })
  extendList.value = data?.map((item) => {
    return {
      ...item,
      presetContentMap: item.presetContent ? JSON.parse(item.presetContent) : []
    }
  })
  getLevelList()
}

const columnList = ref([
  {
    index: '1',
    name: '',
    required: '',
    fillingMethod: '输入框',
    presetContentMap: []
  }
])
// 获取制度信息字段列表
const getAssuranceList = async (template) => {
  const data = await assuranceApi.assurancePage({
    dataStandardId: template || props.params.template,
    display: 1,
    page: 1,
    pageSize: 20
  })
  if (data.length > 0) {
    columnList.value = data
  } else {
    columnList.value = []
  }
}

// 获取等级下拉列表

const levelList = ref([])
const allLevelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  const deadLineConf = extendList.value.find((item) => item.index === 3)
  if (deadLineConf && deadLineConf.presetContent && deadLineConf.presetContent !== '[]') {
    const presetCodes = JSON.parse(deadLineConf.presetContent)
    const arr = data.filter((item) => presetCodes.includes(item.levelCode))
    levelList.value = arr.map((ite) => {
      ite.levelCode = ite.levelCode + ''
      return ite
    })
  } else {
    levelList.value = data.map((ite) => {
      ite.levelCode = ite.levelCode + ''
      return ite
    })
  }
  allLevelList.value = data
}

/** 查询下拉列表 */
const downLists = ref([])
const dropdownData = ref()
const getDownList = async (template) => {
  let data = await valueConfGetByValue({
    dataStandardId: template || props.params.template
  })
  let treeData = await valueConfGetByValueTree({
    dataStandardId: template || props.params.template
  })
  let { inFiledChange, typeChange, byValuetreeData, byValueData, cascaderSelectOptions } =
    useCascader({
      treeData,
      data,
      listValue: toRef(formData, 'list'),
      tempLevelList: tempLevelList.value
    })

  institutionFiledChange = inFiledChange
  classChange = typeChange
  cascaderAllOptions.value = cascaderSelectOptions.value
  if (data.length > 0) {
    downLists.value = byValueData
    flattenDownList.value = byValuetreeData
    dropdownData.value = convertToDropdownData(downLists.value)
  } else {
    downLists.value = data
    flattenDownList.value = []
    classOptions.value = setClassOptionsMap(flattenDownList.value)
  }
}

const convertToDropdownData = (data) => {
  const dropdownData = {}
  Object.keys(data[0]).forEach((key) => {
    if (key.startsWith('field')) {
      if (key.startsWith('field3'))
        dropdownData[key] = Array.from(
          new Set(data.map((item) => item[key]).filter((value) => value !== ''))
        )
    }
  })
  return dropdownData
}

const tempClassList = ref([])
const tempLevelList = ref([])
const levelOptions = ref([])
const getClassLevelList = async (template) => {
  tempClassList.value = await valueConfFieldValue({
    dataStandardId: template || props.params.template,
    type: '1'
  })
  levelOptions.value = await valueConfFieldValue({
    dataStandardId: template || props.params.template,
    type: '2'
  })
  let levelOptionsData = levelOptions.value.map((ite) => {
    return {
      ...ite,
      disabled: false
    }
  })
  tempLevelList.value = levelOptionsData
  // levelOptions.value.map((ite) => {
  //   tempLevelList.value.push({
  //     data: [{
  //       ...ite,
  //       disabled: false

  //     }]
  //   })
  // })
  // tempLevelList.value.map((item) => {
  //   item.data = levelOptions.value.map((ite) => {
  //     return {
  //       ...ite,
  //       disabled: false
  //     }
  //   })
  // })
}

const systemList = ref()
const options = ref()
const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
  form.value.sysId = systemList.value[0]?.id
}
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  options.value = data
  form.value.deptId = data[0]?.id
}

// 数据标准
const templateList = ref([])
const getTemplateList = async () => {
  const { data } = await dataStandardsPage({ page: 1, pageSize: 999, type: 0, status: '1' })
  templateList.value = data
  form.value.template = data[0].id
  templateChange()
}

const setClassOptionsMap = (data) => {
  return data.map((item) => {
    item.field1_name = tempClassList?.value?.find((fitem) => fitem.key == item.field1)?.value
    item.disabled = item.isSelect == '0'
    item.children.length && setClassOptionsMap(item.children)
    return item
  })
}
watch(
  () => [tempClassList.value, downLists.value],
  () => {
    if (downLists.value.length > 0 && tempClassList.value.length > 0) {
      classOptions.value = setClassOptionsMap(flattenDownList.value)
    }
  }
)

onMounted(() => {
  getSystemList()
  getDeptList()
  getTemplateList()
  // getLevelList()
})
</script>

<style scoped lang="scss">
:deep(.el-table .el-form-item--default) {
  margin-bottom: 0 !important;
}
</style>
